import logging
from flask import Blueprint, request, current_app
from app.service.stock_service import fetch_stock_list_from_sina
from app.service.model_service import train_and_predict
import app.utils as utils
from flask_caching import Cache

# 创建蓝图对象
predict_controller = Blueprint('predict_controller', __name__)
cache = Cache(config={'CACHE_TYPE': 'SimpleCache'})

@predict_controller.before_app_request
def init_cache():
    cache.init_app(current_app)

@predict_controller.before_request #请求处理前记录请求信息
def log_request_info():
    current_app.logger.info(f"收到请求: {request.method} {request.url}")

@predict_controller.after_request #响应返回后记录响应状态
def log_response_info(response):
    current_app.logger.info(f"响应状态码: {response.status_code}")
    return response

@predict_controller.get('/update')
def update_stocks():
    """
    自动从网页爬取所有股票代码，抓取历史数据并更新数据库
    """
    try:
        current_app.logger.info("开始更新数据...")
        print('开始存入数据库')
        tickers = fetch_stock_list_from_sina()
        #return utils.success()
    except Exception as e:
        current_app.logger.exception("更新股票数据失败")
        return utils.error("股票数据更新失败", status=500,code=1)
    predictions = {}
    try:
        pred = train_and_predict(tickers)
        print(pred)
        return utils.success(data=pred)
    except Exception as e:
        current_app.logger.exception("预测失败")
        return utils.error("预测失败", status=500, code=1)

